export enum FILTER_CODE {
  /** GT */
  大于 = 1,
  /** GE */
  大于等于 = 2,
  /** LT */
  小于 = 3,
  /** LE */
  小于等于 = 4,
  /** EQ */
  等于 = 5,
  /** LIKE */
  包含 = 6,
  /** NOT_LIKE */
  不包含 = 7,
  /** BETWEEN */
  范围查询 = 8,
  /** IN */
  多值匹配 = 9,
  /** LIKE_LEFT */
  结束以 = 10,
  /** LIKE_RIGHT */
  开始以 = 11,
  /** NE */
  不等于 = 12,
  /** IS_NULL */
  IS_NULL = 13,
  /** IS_NOT_NULL */
  IS_NOT_NULL = 14,
}

export type FilterTypes = 'string' | 'int' | 'date' | 'boolean'

export interface FilterOptions {
  code?: FILTER_CODE
  type?: FilterTypes
  enableFlag?: boolean
}

export interface FilterColumn {
  name: string
  value: any
  type: FilterTypes
  filterOperatorCode: FILTER_CODE
}

export class Query {
  private filterValues: any[] = [null, '', undefined, NaN]
  private filterColumns: FilterColumn[] = []
  constructor(filterValues?: any[]) {
    if (Array.isArray(filterValues)) {
      this.filterValues = filterValues
    }
  }
  public getFilterColumns() {
    return this.filterColumns
  }

  /**
   * 添加查询条件
   * @param name
   * @param value
   * @param param2
   * @returns
   */
  public add(
    name: string,
    value: any = '',
    { code = FILTER_CODE.等于, type = 'string', enableFlag = true }: FilterOptions = {}
  ): Query {
    const invalidCondition =
      this.filterValues.includes(name) ||
      this.filterValues.includes(value) ||
      Boolean(enableFlag) === false
    if (!invalidCondition) {
      this.filterColumns.push({
        name,
        value,
        filterOperatorCode: code,
        type,
      })
    }
    return this
  }

  /**
   * 根据查询字段删除查询条件
   * @param name
   * @returns
   */
  remove(name: string) {
    let index = this.filterColumns.findIndex((item) => item.name === name)
    while (index > -1) {
      this.filterColumns.splice(index, 1)
      index = this.filterColumns.findIndex((item) => item.name === name)
    }
    return this
  }

  /**
   * 合并其他Query 或 查询条件
   * @param query
   */
  public merge(query: Query | FilterColumn[] | FilterColumn): Query {
    if (query instanceof Query) {
      this.filterColumns.push(...query.getFilterColumns())
    } else if (Array.isArray(query)) {
      this.filterColumns.push(...query)
    } else {
      this.filterColumns.push(query)
    }
    return this
  }

  /**
   * 清空查询条件
   * @returns
   */
  public clear(): Query {
    this.filterColumns = []
    return this
  }
}
